package com.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.oss.service.OssService;
import com.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    //上传头像到oss
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //工具类获取值
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;


        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();

            //获取文件名称
            String FileName = file.getOriginalFilename();

            //1.在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            FileName = uuid + FileName;

            //2.把文件按照日期进行分类
            //获取当前日期
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //拼接
            //2022/6/8/qweqwesadsfdfgdf01.jpg
            FileName = datePath + "/" + FileName;

            // 调用oss方法实现上传
            //1.bucket名称
            //2.上传到oss文件路径和文件名称 /aa/b//1.jpg
            ossClient.putObject(bucketName, FileName, inputStream);

            //关闭OSSClient
            ossClient.shutdown();

            //把上传之后文件的路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //https://edu-0352.oss-cn-hangzhou.aliyuncs.com/9c5fe9a7gy1h2hc9h030mj20u016g134.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+FileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
